<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>

<form style="margin:8px 0; display:block" onsubmit="return display(0);">
    <button onmousedown="display(-1)">&laquo;</button>
    <input size="4" value="" maxlength="4">
    <button onmousedown="display(1)">&raquo;</button>
    <input type=submit value="__MSG_Labs_Go_To_Year__" onmousedown="display(0)">
    <button onmousedown="displayCurrentYear()">__MSG_Labs_This_Year_Button__
    </button>
</form>

<div id=calDiv></div>

<script>

    /** The full names of the months to use as titles */
    var MONTH_NAMES = ["__MSG_January__", "__MSG_February__", "__MSG_March__",
        "__MSG_April__", "__MSG_May__", "__MSG_June__", "__MSG_July__",
        "__MSG_August__", "__MSG_September__", "__MSG_October__",
        "__MSG_November__", "__MSG_December__"];

    /** The VERY short names of the weekdays to use as headings */
    var DOW = ["__MSG_Short_Sunday__", "__MSG_Short_Monday__",
        "__MSG_Short_Tuesday__", "__MSG_Short_Wednesday__",
        "__MSG_Short_Thursday__", "__MSG_Short_Friday__",
        "__MSG_Short_Saturday__"];

    /** The lengths of the months */
    var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    var SHOW_MONTH = "__MSG_Labs_Gadget_Month_View_Tooltip__";

    /**
     * Given a date, check if it is a leap year.
     * @param {Date} date The date in question.
     * @return {boolean} Whether it is a leap year.
     */
    function isLeapYear(date) {
        var y = date.getFullYear();
        if ((y % 4) == 0 && (y % 100) != 0) {
            return true;
        }
        return (y % 400) == 0;
    }

    /**
     * Get the number of days in a month.
     * @param {Date} date The date in question.
     * @return {number} The number of days in that month.
     */
    function getDaysInMonth(date) {
        var days = DAYS_IN_MONTH[date.getMonth()];
        return (days == 28 && isLeapYear(date)) ? 29 : days;
    }

    /**
     * Get the text input for the year.
     * @return {HTMLElement} The element.
     */
    function getYearInput() {
        return document.getElementById('yearInput');
    }

    /**
     * Display the current year.
     * @param {string} opt_override An override year.
     */
    function displayCurrentYear(opt_override) {
        var year = opt_override || (new Date()).getFullYear();
        currentYear = year;
        getYearInput().value = year;
        showYear(year);
    }

    var currentYear = (new Date()).getFullYear();

    /**
     * Display a year offset from the current one.
     * @param {number} delta How many years to move.
     */
    function display(delta) {
        var yearInput = getYearInput();
        yearInput.value.replace(/[^0-9]/g, '');
        var y = parseInt(yearInput.value, 10) + delta;
        if (isNaN(y) || y > 9999 || y < 1) {
            yearInput.value = '?';
        } else {
            yearInput.value = y;
            showYear(y);
        }
        return false;
    }

    /**
     * How many weeks does a given month overlap?
     * @param {number} y The year.
     * @param {number} m The month.
     * @return {number} The number of weeks that the month overlap.
     */
    function getWeeksInMonth(y, m) {
        var firstDate = new Date(y, m, 1);
        var firstDayOfMonth = firstDate.getDay();
        var daysInMonth = getDaysInMonth(firstDate);

        return Math.ceil((firstDayOfMonth + daysInMonth) / 7)
    }

    /**
     * Ask the calendar to go to a specific date
     */
    function showDate(y, m, opt_date) {
        if (google && google.calendar) {
            google.calendar.showDate(y, m, opt_date || 1);
        }
    }

    /**
     * Get the HTML for a specific month.
     * @param {Array<string>} out The string buffer to append the output.
     * @param {number} y The year.
     * @param {number} m The month.
     */
    function getMonthHtml(out, y, m) {
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth();
        var todayDate = today.getDate();


        out.push('<table class="month" border=0 cellspacing=0>',
                '<tr><td colspan=5 title="',
                SHOW_MONTH, '" class="monthHeader clickable" ',
                'onclick="showDate(', y, ',', m + 1, ')">', MONTH_NAMES[m], ' ', y,
                '</td>', '</tr>');

        var firstDate = new Date(y, m, 1);
        var firstDayOfMonth = firstDate.getDay();
        var daysInMonth = getDaysInMonth(firstDate);
        var i = firstDayOfMonth % 7;

        output = "month :" + (m + 1) + "\n";
        for (var d = 1; d <= daysInMonth; ++d) {
            var dow = i % 7;

            out.push('<tr>');

            out.push('<td class="dow" style="color:black">', DOW[dow], '</td>');

            out.push('<td colspan=4');
            out.push(" id='" + y + "-" + (m + 1) + "-" + d + "' ");

            out.push('class="');
            var c = 'normal';
            if (y == todayYear && m == todayMonth && d == todayDate) {
                c = 'today';
            }
            if ((d <= daysInMonth) && ((dow == 0) || (dow == 6))) {
                c = 'weekend ';
            }

            out.push(c);

            out.push(' clickable" onclick="showDate(', y, ',', m + 1, ',', d,
                    ')">', d, '</td>');

            out.push('</tr>');

            i++;
        }

        //var output = "month: "+(m+1)+" ";
        //for(x in monthEvents) {
        //  output += x + " " + monthEvents[x] + "\n";
        //}
        //alert(output);

        out.push('</td>');
        out.push('</table>');
    }

    /**
     * This is the main drawing function. It will display a specific year.
     * @param {number} year The year to draw.
     */
    function showYear(y) {
        var out = ['<table>'];
        for (var m = 0; m < 12; ++m) {
            out.push('<td class="outer">');
            getMonthHtml(out, y, m);
            out.push('</td>');
        }

        out.push('</table>');
        document.getElementById('calDiv').innerHTML = out.join('');

        month = 1;
        getMonthEvents();
    }

    var month = 1;

    function getMonthEvents() {
        if (month <= 12) {
            year = currentYear;
            nxtMonth = parseInt(month) + 1;
            nxtYear = year;
            if (nxtMonth > 12) {
                nxtMonth = 1;
                nxtYear = parseInt(year) + 1;
            }

            startDate = {year: year, month: month, date: 1, hour: 0, minute: 0, second: 0};
            endDate = {year: nxtYear, month: nxtMonth, date: 1, hour: 0, minute: 0, second: 0};
            google.calendar.read.getEvents(eventCallback, "selected", startDate, endDate);
            month = parseInt(month) + 1;
        }
    }

    // Setup the style + buttons
    var DARK_BLUE = '#112aba';
    var LIGHT_BLUE = '#e8eef7';
    var WEEKEND = '#eee';
    var WHITE = '#fff';
    var TODAY = '#557799';
    var TODAY_BORDER_DARK = '#246';
    var TODAY_BORDER_LIGHT = '#9bd';
    var BORDER_GREY = '#a2bbd3';
    var DIVIDER = '#c3d9ff';

    /**
     * @return {string} A string containing the styles.
     */
    function getStyles() {
        var out = ['<style>'];
        out.push(
                //'html, body { height: 100%;}',
                '.month td {text-align: center; padding:2px 4px 1px}',
                '.month,td.dow,td.monthHeader {background-color:', LIGHT_BLUE, '}',
                'td.normal {background-color:', WHITE, '}',
                'td.weekend {background-color:', WEEKEND, '}',
                'td.outer {padding-right: 4px; padding-bottom: 4px; }',
                'td.dow {max-width: 5px; border-width: 0 0 1px 0; border-style:solid;',
                'border-color: ', DIVIDER, '}',
                'td.today {padding: 1px 3px !important; background-color:', TODAY,
                ';color:#fff !important; border-width: 1px; border-style:solid;',
                'border-color: ', TODAY_BORDER_DARK, ' ', TODAY_BORDER_LIGHT, ' ',
                TODAY_BORDER_LIGHT, ' ', TODAY_BORDER_DARK, '}',
                'td.monthHeader {font-weight:bold}',
                '.month {table-layout: fixed; width: 100%; background-color:', LIGHT_BLUE,
                ';border: 1px solid ', BORDER_GREY, '}',
                'body, td {font-family:Arial;font-size: 12.8px}',
                'body {margin-left:10px; background-color:', WHITE, '}',
                'td {vertical-align: top}',
                '.clickable {cursor:pointer; color:', DARK_BLUE, '}',
                '.clickable:hover {text-decoration: underline}',
                '.busy {color: red; }');
        out.push('</style>');
        return out.join('');
    }


    document.write(getStyles());

    var tentativeYear = gadgets.views.getParams()['year'];
    displayCurrentYear(tentativeYear);

    // This is here to make it look nicer for gmail
    gadgets.window.adjustHeight(2600);

    //for(i=1; i<=12; i++ ) {
    //	year = tentativeYear;
    //	month = i;
    //	nxtMonth = parseInt(month)+1;
    //	nxtYear = year;
    //	if(nxtMonth > 12) {
    //		nxtMonth = 1;
    //		nxtYear = parseInt(year)+1;
    //	}
    //	startDate = {year: year, month: month, date: 1, hour: 0, minute: 0, second: 0};
    //	endDate = {year: nxtYear, month: nxtMonth, date: 1, hour: 0, minute: 0, second: 0};
    //	google.calendar.read.getEvents(eventCallback, "selected", startDate, endDate);
    //}

    function eventCallback(response) {

        for (var cal = 0; cal < response.length; ++cal) {

            if ('error' in response[cal]) {
                alert('Something went wrong ' + response[cal]['error']);
                return;
            }

            var events = response[cal]['events'];

            var output = "";
            for (var i = 0; i < events.length; ++i) {

                var e = events[i];
                if ('title' in e) {
                    var startDate = new Date(e.startTime.year, (e.startTime.month - 1), e.startTime.date);
                    var endDate = new Date(e.endTime.year, (e.endTime.month - 1), e.endTime.date);

                    var currentDate = startDate;//new Date(startDate.getTime());
                    while (currentDate.getTime() <= endDate.getTime()) {
                        id = currentDate.getFullYear() + "-" + (currentDate.getMonth() + 1) + "-" + currentDate.getDate();
                        // prevent double entries
                        if ((currentDate.getDate() == endDate.getDate() && e.allDay == true) || (currentDate.getMonth() + 2) != month) {
                            currentDate.setDate(currentDate.getDate() + 1);
                            continue;
                        }

                        document.getElementById(id).className += " busy ";
                        document.getElementById(id).title += e.title + " " + e.startTime.date + " " + e.endTime.date + "; \n";
                        document.getElementById(id).innerText += "\n" + e.title.substr(0, 14);

                        currentDate.setDate(currentDate.getDate() + 1);

                    }
                }
            }
        }
        getMonthEvents();
    }

</script>

</body>
</html>